import re
from rest_framework import serializers
from rest_framework import status
from rest_framework.response import Response
from django_redis import get_redis_connection
from oauth.models import OAuthQQUser
from oauth.utils import check_save_user_token
from users.models import User


class QQAuthUserSerializer(serializers.Serializer):
    """QQ登陆创建序列化器"""
    # write_only仅限于客户端提交
    access_token = serializers.CharField(label='操作凭证', write_only=True, help_text='jwt token')
    mobile = serializers.RegexField(label='手机号码', regex='^1[3-9]\d{9}')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码')

    def validate_access_token(self, value):
        # value是加密后的access_token
        # 1. 校验access_token
        openid = check_save_user_token(value)
        print(openid)
        if openid is None:
            raise serializers.ValidationError({'message': 'access_token无效'})
        return openid

    def validate(self, atts):
        """
        校验参数
        :param atts:
        :return: atts
        """
        # １,校验手机号
        print(atts.get('access_token'))
        mobile = atts.get('mobile')
        if not re.match(r'^1[3-9]\d{9}', mobile):
            return Response({'message': '手机号格式错误'}, status=status.HTTP_400_BAD_REQUEST)
        # 2,校验短信验证码
        sms_code = atts.get('sms_code')
        # 2.1获取真实的验证码
        redis_sms_code = get_redis_connection('verify_codes')
        try:
            real_sms_code = redis_sms_code.get('sms_%s' % mobile)
            real_sms_code = real_sms_code.decode()
        except Exception as e:
            return serializers.ValidationError('短信验证码无效')
        else:
            if sms_code != real_sms_code:
                raise serializers.ValidationError('收入验证码错误')
        # 3. 判断美多账号是否存在
        try:
            user = User.objects.get(mobile=mobile)
            # 把用户存起来后续用到
            atts['user'] = user
        except User.DoesNotExist:
            # 不存在的美多账号，则创建美多账号
            # 创建美多账号，可以在下方的create方法中实现，所以这里不需要处理异常，因此pass
            pass
        return atts

    # 3.2 美多账号不存在，则新增账号密码，把手机号码作为账号[添加]
    def create(self, validated_data):
        user = validated_data.get('user')
        if user is None:
            user = User.objects.create(
                username=validated_data['mobile'],
                password=validated_data['password'],
                mobile=validated_data['mobile'],
            )
            # 新增的美多账号都要密码加密
            user.set_password(validated_data['password'])
            user.save()
        # 4. 把美多账号和QQ的openID进行绑定到auth_qq表中[添加数据]
        OAuthQQUser.objects.create(
            openid=validated_data['access_token'],
            user=user
        )
        # 在视图中返回jwt
        return user
